package com.mycompany.managedbean;

import com.mongodb.DBCollection;
import static com.mycompany.managedbean.Connector.client;
import static com.mycompany.managedbean.Connector.database;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.event.ActionEvent;
import org.primefaces.context.RequestContext;
import org.primefaces.event.SelectEvent;

/**
 *
 * @author Muharrem Tigdemir
 */
@ManagedBean
@ViewScoped
public class LazyTableBean implements Serializable {

    private static final long serialVersionUID = 7863262235394607247L;
    private LazyDataObjectModel lazymodel;
    @ManagedProperty(value = "#{mainController}")
    private MainController controller;
    private String collectionName = new String();
    private String databaseName = new String();
    private DataObject selectedDataObject;

    public LazyTableBean() {
        System.err.println("Construct");
        RequestContext context = RequestContext.getCurrentInstance();  
        context.update("form:myDatatable");  
    }

    public void generateTable() {
        setCollectionName(controller.getSelectedNode().getData().toString());
        setDatabaseName(controller.getSelectedNode().getParent().toString());

        /*Trigger Table*/
        System.err.println("Triggered");
        lazymodel = new LazyDataObjectModel(databaseName, collectionName);
        RequestContext context = RequestContext.getCurrentInstance();  
        context.update("form:myDatatable");  
    }

    public void onRowSelect(SelectEvent event) {
        selectedDataObject = (DataObject) event.getObject();
    }

    public void deleteDataObject() {
        database = client.getDB(databaseName);
        DBCollection coll = database.getCollection(collectionName);
        coll.remove(selectedDataObject.getDbObject());
    }

    /*Getter Setters*/
    public LazyDataObjectModel getLazymodel() {
        return lazymodel;
    }

    public void setLazymodel(LazyDataObjectModel lazymodel) {
        this.lazymodel = lazymodel;
    }

    public MainController getController() {
        return controller;
    }

    public void setController(MainController controller) {
        this.controller = controller;
    }

    public String getCollectionName() {
        return collectionName;
    }

    public void setCollectionName(String collectionName) {
        this.collectionName = collectionName;
    }

    public String getDatabaseName() {
        return databaseName;
    }

    public void setDatabaseName(String databaseName) {
        this.databaseName = databaseName;
    }

    public DataObject getSelectedDataObject() {
        return selectedDataObject;
    }

    public void setSelectedDataObject(DataObject selectedDataObject) {
        this.selectedDataObject = selectedDataObject;
    }

}
